package com.nova.bluetooth.ui.ai.aiNote;


import static com.nova.bluetooth.xunFeiSDK.engine.EngineConstants.RECORDER_DATA;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.lifecycle.ViewModelProvider;

import com.gyf.immersionbar.ImmersionBar;
import com.nova.bluetooth.MyApp;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.CommonMessageWrap;
import com.nova.bluetooth.databinding.ActivityVoiceToTextBinding;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;
import com.nova.bluetooth.rtasrWSS.XunFeiRTASRManager;
import com.nova.bluetooth.ui.ai.MyAiUiViewModel;
import com.nova.bluetooth.widget.CommonDialog;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class VoiceToTextActivity extends PermissionManageActivity implements MyAiUiViewModel.OnAiUiRecognizeListener,
        XunFeiRTASRManager.OnRTASRResultListener {
    private XunFeiRTASRManager mRtasrManager;
    private ActivityVoiceToTextBinding binding;
    private ImmersionBar mImmersionBar;
    private String saveRecordPath;
    private String newSaveRecordPath;
    private MyAiUiViewModel aiUiViewModel;
    int offHeight;
    int offTopHeight;
    private File musicDir;
    private String mTempContent;
    private String mTempFileText;
    private volatile boolean isTemp;
    private long activityOnLineTime;  //记录启动界面时间

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        EdgeToEdge.enable(this);
        activityOnLineTime = System.currentTimeMillis();
        initBinding();
        setContentView(binding.getRoot());
        initView();
        initData();
        observe();

        mRtasrManager = XunFeiRTASRManager.getInstance();
        XunFeiRTASRManager.isTranslate = false;
        mRtasrManager.setOnRTASRResultListener(this);
        setRTASRConfig();
    }


    private void observe() {
    }

    private void initBinding() {
        binding = ActivityVoiceToTextBinding.inflate(getLayoutInflater());
        aiUiViewModel = new ViewModelProvider(MyApp.getInstance()).get(MyAiUiViewModel.class);
//        aiUiViewModel = new ViewModelProvider(this).get(AiUiViewModel.class);
        binding.setOnClick(new MyOnClickEvent());
    }

    private void initView() {
        EngineConstants.saveAudio = true;
        aiUiViewModel.initSDK(this);
        EventBusUtil.register(this);
    }


    @SuppressLint("MissingPermission")
    @Override
    public void onDestroy() {
        EngineConstants.saveAudio = false;
        EventBusUtil.unRegister(this);
        super.onDestroy();
        mRtasrManager.clearData();
        mRtasrManager.onDestroy();
        aiUiViewModel.destroyAiUiAllEngine();
    }

    boolean isStartFromDevice = false;

    private void initData() {
    }

    @Override
    public void onAsrResult(String result) {
//        if (dialogRealTimeRecordingToText != null) {
//            dialogRealTimeRecordingToText.setAsrResult(result);
//        }
    }

    @Override
    public void onRecordStatus(boolean recording) {
    }

    /****************************RTASR start******************************/
    @Override
    public void onRTASRResult(String result, StringBuffer bufferResult) {

    }

    @Override
    public void onRTASRTranslateResult(String result, StringBuffer bufferResult) {

    }

    private StringBuffer type_0_data = new StringBuffer();

    @Override
    public void onRTASRShortResult(String result, int type) {
        if (type == 0) {
            type_0_data.append(result);
            result = "";
        }

        String finalResult = result;
        binding.getRoot().post(() -> {
            binding.etContent.setText(type_0_data.toString() + finalResult);
            binding.etContent.scrollToBottom();

            if (binding.layoutEmpty.getVisibility() == View.VISIBLE) {
                binding.layoutEmpty.setVisibility(View.GONE);
                binding.btnOutput.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onRTASRTranslateShortResult(String result, int type) {

    }
    /****************************RTASR end******************************/

    /********************************语言选择start*********************************/

    private String asrLanguage = "cn";
    private int asrLanguageType = 1;
    private String translateLanguage = "en";
    private boolean isTranslate = false;
    private boolean translateLanguageUnable = true;  //翻译语言是否可用

    /**
     * 更新实时语音转写参数，参数改变都应该调用该方法更新下
     */
    private void setRTASRConfig() {
        XunFeiRTASRManager.isTranslate = isTranslate;
        XunFeiRTASRManager.RTASR_LANG = asrLanguage;
        XunFeiRTASRManager.RTASR_TRANSLATE_LANG = translateLanguage;
    }

    /********************************语言选择end*********************************/

    private void stopRecordAndRecognize() {
        aiUiViewModel.clearRecognitionText();
        stopRecord();
    }

    private void stopRecord() {
        aiUiViewModel.stopRecord();
        mRtasrManager.stopRTASRManager();
        binding.ivAudioPlay.setSelected(false);
    }

    private void showPermissionRequiresDialog() {
        getRecordAudioPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                initAiUiRecord();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取录音权限用于录音翻译");
    }

    private void deleteSaveRecordFile() {
        if (TextUtils.isEmpty(saveRecordPath)) {
            return;
        }
        File file = new File(saveRecordPath);
        if (file.exists()) {
            file.delete();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommonMessageWrap message) {
        switch (message.getEventCode()) {
            case RECORDER_DATA:
                byte[] audioData = (byte[]) message.getObject();
                //可用于根据声音大小制作振幅动效图
                break;
        }
    }

    private void initAiUiRecord() {
        mRtasrManager.startWebSocketClient();

        //初始化录音(唤醒直接识别)
        aiUiViewModel.initRecorder();
        binding.ivAudioPlay.setSelected(true);
    }


    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    private void doBtnSave() {
        stopRecord();
        getReadMediaPermission(new com.nova.bluetooth.permission.OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                showOutputLogDialog();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {
                ToastUtils.show("未获得文件读写权限，无法操作下一步");
            }
        }, "");
    }

    private void showOutputLogDialog() {
        CommonDialog dialog = new CommonDialog(this, R.layout.dialog_output_log);
        dialog.setWidth(R.dimen.dp_320);
        dialog.setCancelable(true);
        dialog.setGravity(Gravity.CENTER);
        dialog.showDialog();

        TextView title = dialog.getDialog().findViewById(R.id.tv_title);
        title.setText("导出识别结果");
        TextView tips = dialog.getDialog().findViewById(R.id.tv_tips);
        dialog.getDialog().findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismissDialog();
            }
        });
        dialog.getDialog().findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveContentToFile(binding.etContent.getText().toString());
                dialog.dismissDialog();
            }
        });
    }

    public void saveContentToFile(String content) {
        new Thread(() -> {
            String fileName = "语音识别结果_" + System.currentTimeMillis() + ".txt";
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileName);

            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(content.getBytes());
                Log.d("PermissionActivity", "saveContentToFile: " + file.getAbsolutePath());
                runOnUiThread(() -> ToastUtils.show("已保存到: " + file.getAbsolutePath()));
            } catch (IOException e) {
                runOnUiThread(() -> ToastUtils.show("保存失败: " + e.getMessage()));
            }
        }).start();
    }


    public class MyOnClickEvent extends OnClickEvent {

        @Override
        public void singleClick(View v) {
            int id = v.getId();
            if (id == R.id.iv_back) {
                finish();
            } else if (id == R.id.iv_audio_play) {
                boolean isSelected = binding.ivAudioPlay.isSelected();
                if (isSelected) {
                    stopRecord();
                } else {
                    showPermissionRequiresDialog();
                }
            } else if (id == R.id.btn_output) {
                doBtnSave();
            }
        }
    }
}
